package com.qf.security.handler;

import com.qf.aop.async.AsyncTaskFactory;
import com.qf.api.entity.SysRoleEntity;
import com.qf.api.entity.SysUserEntity;
import com.qf.api.vo.LoginResultVO;
import com.qf.core.enums.common.LoginStatusEnum;
import com.qf.core.response.ResponseResult;
import com.qf.core.thread.ThreadPoolManager;
import com.qf.core.utils.BeanUtils;
import com.qf.core.utils.ServletUtils;
import com.qf.security.SysLoginUser;
import com.qf.security.jwt.util.JwtUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: sin
 * @Date: 2025/5/5 22:12
 * @Description: 自定义登录成功响应
 **/
@Slf4j
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//        log.info("登录成功");
        if (authentication.getPrincipal() instanceof SysLoginUser loginUser) {
            SysUserEntity user = loginUser.getUser();
            //log.info("登录成功，用户信息：{}", sysUser);
            // 获取token  封装
            List<String> roles = user.getRoles().stream().map(SysRoleEntity::getCode).collect(Collectors.toList());
            //获取当前时间戳
            Long expireTime = BeanUtils.getBean(JwtUtil.class).getExpireTime();
            //封装token
            String accessToken = BeanUtils.getBean(JwtUtil.class).token(authentication);
            String refreshToken = BeanUtils.getBean(JwtUtil.class).refreshToken(authentication);
            // 记录登录成功日志
            ThreadPoolManager.execute(BeanUtils.getBean(AsyncTaskFactory.class).loginInfoTask(user.getUsername(), LoginStatusEnum.LOGIN_SUCCESS,LoginStatusEnum.LOGIN_SUCCESS.description()));
            // 通过响应流封装数据返回给前端
            ServletUtils.renderString(response, ResponseResult.success(new LoginResultVO(user.getUsername(), user.getAvatar(), user.getNickname(), roles, user.getPerms(), accessToken, refreshToken, expireTime)));
        }
    }
}
